package com.mihuxiaobaigao.ai.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

public class BoxControlUtils {

    private final String hardwareIp = "192.168.1.39"; // 硬件IP
    private final int hardwarePort = 5000; // 硬件端口
    private final ObjectMapper objectMapper = new ObjectMapper();
    private Socket socket;
    private PrintWriter writer;

    // 线程池用于定时任务
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);

    // 记录箱子的定时关闭任务
    private final Map<Integer, ScheduledFuture<?>> boxCloseTasks = new ConcurrentHashMap<>();

    /**
     * 初始化TCP连接
     */
    private void initializeConnection() {
        try {
            InetAddress address = InetAddress.getByName(hardwareIp);
            boolean reachable = address.isReachable(5000); // 5秒超时
            System.out.println("IP地址是否可达: " + reachable);

            if (reachable) {
                socket = new Socket(hardwareIp, hardwarePort);
                writer = new PrintWriter(socket.getOutputStream(), true);
            } else {
                System.out.println("网络不通，请检查IP地址和网络连接");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送控制指令到硬件
     */
    private boolean sendCommand(int box, String operation) {
        try {
            if (writer == null) {
                initializeConnection();
            }

            // 构造JSON数据：{"box": 0, "op": "open"}
            Map<String, Object> command = new HashMap<>();
            command.put("box", box);
            command.put("op", operation);

            String jsonCommand = objectMapper.writeValueAsString(command);
            System.out.println("发送指令: " + jsonCommand);

            writer.println(jsonCommand);
            writer.flush();

            return true;

        } catch (Exception e) {
            System.err.println("发送指令失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 打开箱子1
     */
    public boolean openBox1() {
        return sendCommand(0, "open");
    }

    /**
     * 关闭箱子1
     */
    public boolean closeBox1() {
        cancelAutoCloseTask(0);
        return sendCommand(0, "close");
    }

    /**
     * 打开箱子2
     */
    public boolean openBox2() {
        return sendCommand(1, "open");
    }

    /**
     * 关闭箱子2
     */
    public boolean closeBox2() {
        cancelAutoCloseTask(1);
        return sendCommand(1, "close");
    }

    /**
     * 打开箱子1，10秒后自动关闭
     */
    public boolean openBox1WithAutoClose() {
        return openBoxWithAutoClose(0, 4);
    }

    /**
     * 打开箱子2，10秒后自动关闭
     */
    public boolean openBox2WithAutoClose() {
        return openBoxWithAutoClose(1, 4);
    }

    /**
     * 打开指定箱子并设置自动关闭
     */
    private boolean openBoxWithAutoClose(int boxNumber, int delaySeconds) {
        // 先取消旧的定时任务
        cancelAutoCloseTask(boxNumber);

        // 发送开门指令
        boolean openSuccess = sendCommand(boxNumber, "open");

        if (openSuccess) {
            System.out.println("箱子" + (boxNumber + 1) + "打开成功，" + delaySeconds + "秒后自动关闭");

            // 启动定时关闭任务
            ScheduledFuture<?> future = scheduler.schedule(() -> {
                sendCommand(boxNumber, "close");
                System.out.println("箱子" + (boxNumber + 1) + "已自动关闭");
            }, delaySeconds, TimeUnit.SECONDS);

            // 保存定时任务引用
            boxCloseTasks.put(boxNumber, future);
        }

        return openSuccess;
    }

    /**
     * 取消自动关闭任务
     */
    private void cancelAutoCloseTask(int boxNumber) {
        ScheduledFuture<?> future = boxCloseTasks.get(boxNumber);
        if (future != null && !future.isDone()) {
            future.cancel(false);
            System.out.println("取消箱子" + (boxNumber + 1) + "的自动关闭任务");
        }
        boxCloseTasks.remove(boxNumber);
    }

    /**
     * 手动提前关闭所有箱子
     */
    public void closeAllBoxes() {
        closeBox1();
        closeBox2();
    }

    /**
     * 关闭连接
     */
    public void shutdown() {
        // 关闭所有箱子
        closeAllBoxes();

        // 关闭线程池
        scheduler.shutdown();

        // 关闭TCP连接
        try {
            if (writer != null) writer.close();
            if (socket != null) socket.close();
        } catch (IOException e) {
            System.err.println("关闭连接异常: " + e.getMessage());
        }
    }
}
